#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

void SLInit(SL* sl)
{
	sl->a = NULL;
	sl->size = sl->capacity = 0;
}
void SLDestory(SL* sl)
{
	if (sl->a)
	{
		free(sl->a);
	}
	sl->a = NULL;
	sl->size = sl->capacity = 0;
}

void SLPrint(SL* sl)
{
	assert(sl);
	assert(sl->size);
	for (int i = 0; i < sl->size; i++)
	{
		printf("%d ", sl->a[i]);
	}
	printf("\n");
}

void SLCheckCapacity(SL* sl)
{
	assert(sl);
	if (sl->size == sl->capacity)
	{
		int newCapacity = sl->capacity == 0 ? 4 : sl->capacity * 2;
		SLDataType* tmp = (SLDataType*)realloc(sl->a, newCapacity * sizeof(SLDataType));
		if (tmp == NULL)
		{
			perror("realloc fail!");
			exit(1);
		}
		sl->a = tmp;
		sl->capacity = newCapacity;
	}

}
void SLPushBack(SL* sl, SLDataType x)
{
	SLCheckCapacity(sl);

	sl->a[sl->size] = x;
	sl->size++;
}
void SLPushFront(SL* sl, SLDataType x)
{
	SLCheckCapacity(sl);

	int end = sl->size;
	while (end != 0)
	{
		sl->a[end] = sl->a[end - 1];
		end--;
	}
	sl->a[0] = x;
	sl->size++;
}

void SLPopBack(SL* sl)
{
	assert(sl);
	assert(sl->size);
	sl->size--;
}
void SLPopFront(SL* sl)
{
	assert(sl);
	assert(sl->size);
	int start = 0;
	while (start < sl->size)
	{
		sl->a[start] = sl->a[start + 1];
		start++;
	}
	sl->size--;
}

void SLInsert(SL* sl, int pos, SLDataType x)
{
	assert(sl);
	SLCheckCapacity(sl);
	int end = sl->size;
	while (end >= pos)
	{
		sl->a[end] = sl->a[end - 1];
		end--;
	}
	sl->a[pos] = x;
	sl->size++;
}
void SLErase(SL* sl, int pos)
{
	assert(sl);
	assert(sl->size != 0 && pos >= 0);
	int start = pos;
	while (start < sl->size)
	{
		sl->a[start] = sl->a[start + 1];
		start++;
	}
	sl->size--;
}

int SLFind(SL* sl, SLDataType x)
{
	assert(sl);
	assert(sl->size);
	for (int i = 0; i < sl->size; i++)
	{
		if (sl->a[i] == x)
		{
			return i;
		}
	}
	return -1;
}
